<?php

namespace app;

use libs\HttpRequest;

class QueryPhone
{
    const phone_api_url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";

    public static function query($phone)
    {
        $date = false;
        if (self::verifyPhone($phone)) {
            if (self::selectMysql($phone)) {
                $date = self::selectMysql($phone);
                $date['telString'] = $phone;
                $date['msg'] = "本数据由数据库提供！";
            } else {
                $res = HttpRequest::request(self::phone_api_url, ['tel' => $phone]);
                $res = self::transformCoding($res);
                $date = self::formatDate($res);
                $date['msg'] = "本数据由API提供！";
                self::insertMysql($date);
            }

        }
        return $date;
    }

    public static function verifyPhone($phone)
    {
        $ret = false;
        if ($phone) {
            $pattern = '/^1\d{10}$/';
            if (preg_match($pattern, $phone)) {
                $ret = true;
            }
        }
        return $ret;
    }

    public static function selectMysql($phone)
    {
        $mts = substr($phone, 0, 7);
        //建立与mysql的连接
        $mysqli = new \mysqli(db_server, db_username, db_password, db_datebasename);
        if ($mysqli->connect_errno) {
            die('连接数据库出错：' . $mysqli->connect_error);
        }

        //设置默认编码
        $mysqli->set_charset('utf8');

        // 选取数据
        $result = $mysqli->query("SELECT * FROM api.phone WHERE mts='{$mts}'");
        $row = $result->fetch_assoc();
        return $row;

    }

    public static function transformCoding($date)
    {
        $res = iconv("GBK", "UTF-8", $date);
        return $res;
    }

    public static function formatDate($date)
    {
        $ret = false;
        if ($date) {
            $pattern = '/(\w+):\'([^\']+)/';
            preg_match_all($pattern, $date, $res);
            $ret = array_combine($res[1], $res[2]);
        }
        return $ret;
    }

    public static function insertMysql($date)
    {
        //建立与mysql的连接
        $mysqli = new \mysqli(db_server, db_username, db_password, db_datebasename);
        if ($mysqli->connect_errno) {
            die('连接数据库出错：' . $mysqli->connect_error);
        }

        //设置默认编码
        $mysqli->set_charset('utf8');

        //插入记录
        $sql = "INSERT INTO api.phone(mts,province,catName)VALUES(
'{$date['mts']}',
'{$date['province']}',
'{$date['catName']}'
)";
        if ($mysqli->query($sql)) {
            return true;
        } else {
            return false;
        }

    }


}